package com.zhuguowei.chapter_2_4.aidl;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.zhuguowei.chapter_2_4.R;

import java.util.List;

public class BookManagerActivity extends AppCompatActivity {

    private static final String TAG = "BookManagerActivity";
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;
    private IBookManager mRemoteBookManager;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.e(TAG, "---------新书到啦: " + msg.obj );
                    Log.e(TAG, "-----------------------目前书的列表：--------------------");
                    List<Book> newBookList = null;
                    try {
                        newBookList = mRemoteBookManager.getBookList();
                        Log.e(TAG, "list type : " + newBookList.getClass().getCanonicalName());
                        Log.e(TAG, "onServiceConnected: bookList size = " + newBookList.size());
                        for (int i = 0; i < newBookList.size(); i++) {
                            Log.e(TAG, "-------------------------------------------");
                            Log.e(TAG, newBookList.get(i).toString());
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
    
    //Binder死亡监听，(在客户端的Binder线程池中回调，不能操作UI) zgw-2017/12/4 16:56
    IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            Log.e(TAG, "binderDied: threadName:" + Thread.currentThread().getName() );
            if (mRemoteBookManager == null) {
                return;
            }
            mRemoteBookManager.asBinder().unlinkToDeath(mDeathRecipient,0);
            mRemoteBookManager = null;
            // TODO: 2017/12/4 重新绑定远程服务Service 
        }
    };

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            IBookManager iBookManager = IBookManager.Stub.asInterface(service);
            try {
                mRemoteBookManager = iBookManager;
                //Binder死亡监听 zgw-2017/12/4 17:01
                mRemoteBookManager.asBinder().linkToDeath(mDeathRecipient,0);
                //注意服务端的方法getBookList会产生耗时的操作，一般调用服务端耗时的方法需开启线程 zgw-2017/12/4 16:08
                List<Book> bookList = iBookManager.getBookList();
                Log.e(TAG, "list type : " + bookList.getClass().getCanonicalName());
                Log.e(TAG, "onServiceConnected: bookList size = " + bookList.size());
                for (int i = 0; i < bookList.size(); i++) {
                    Log.e(TAG, "-------------------------------------------");
                    Log.e(TAG, bookList.get(i).toString());
                }
                Log.e(TAG, "======================================");
                iBookManager.addBook(new Book(3, "安卓艺术开发与探索"));
                List<Book> newBookList = iBookManager.getBookList();
                Log.e(TAG, "list type : " + newBookList.getClass().getCanonicalName());
                Log.e(TAG, "onServiceConnected: bookList size = " + newBookList.size());
                for (int i = 0; i < newBookList.size(); i++) {
                    Log.e(TAG, "-------------------------------------------");
                    Log.e(TAG, newBookList.get(i).toString());
                }
                Log.e(TAG, "onServiceConnected: register listener：" + mOnNewBookArrivedListener);
                mRemoteBookManager.registerListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mRemoteBookManager = null;
            Log.e(TAG, "onServiceDisconnected: binder died.");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_manager);
        Intent service = new Intent(this, BookManagerService.class);
        bindService(service, mConnection, BIND_AUTO_CREATE);
    }

    private IOnNewBookArrivedListener mOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            //[onNewBookArrived方法运行在客户端的Binder线程池，不能直接访问UI，需通过Handler切换到UI线程] zgw-2017/12/4 16:11
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED, book).sendToTarget();
        }
    };

    @Override
    protected void onDestroy() {
        if (mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()) {
            try {
                Log.e(TAG, "onDestroy: unregister listener：" + mOnNewBookArrivedListener);
                mRemoteBookManager.unregisterListener(mOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }

    public void onButton1Click(View view) {
        Toast.makeText(this, "click button1", Toast.LENGTH_SHORT).show();
        if (mRemoteBookManager != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<Book> bookList = mRemoteBookManager.getBookList();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
